const { defineConfig } = require('@vue/cli-service')

const webpack = require('webpack')
const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = defineConfig({
  productionSourceMap: false, // 关闭生产环境下的 sourceMap
  transpileDependencies: true,
  runtimeCompiler: true, // 处理runtime版本的render问题
  configureWebpack: {
    externals: {
      jquery: 'jQuery',
      'hls.js': 'hls.js'
    },
    plugins: [
      new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn|ja/),
      new CompressionPlugin({
        test: /\.(js|css)(\?.*)?$/i, //需要压缩的文件正则
        threshold: 1024, //文件大小大于这个值时启用压缩
        deleteOriginalAssets: false //压缩后保留原文件
      }),
      new BundleAnalyzerPlugin()
    ],
    module: {
      rules: [
        {
          test: /\.mjs$/,
          include: /node_modules/,
          type: 'javascript/auto'
        }
      ]
    }
    // optimization: {
    //   usedExports: true
    // }
  },
  chainWebpack(config) {
    // 删除注释和打印日志等一些不必要的信息
    config.optimization.minimizer('terser').tap((args) => {
      args[0].terserOptions.compress.drop_console = true
      args[0].terserOptions.compress.drop_debugger = true
      args[0].terserOptions.compress.pure_funcs = ['console.log']
      args[0].terserOptions.output = {
        comments: false
      }
      return args
    })

    if (process.env.NODE_ENV === 'production') {
      config.optimization.splitChunks({
        cacheGroups: {
          common: {
            //commons 一般是是个人定义的
            name: 'chunk-common', // 打包后的文件名
            chunks: 'initial',
            minChunks: 1,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 1,
            reuseExistingChunk: true
          },
          vendors: {
            //vendor 是导入的 npm 包
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            maxSize: 600000,
            maxInitialRequests: 20,
            priority: 2,
            reuseExistingChunk: true,
            enforce: true
          }
        }
      })
    }

    // const imagesRule = config.module.rule('images')
    // imagesRule
    //   .use('url-loader')
    //   .loader('url-loader')
    //   .options({
    //     bypassOnDebug: true
    //   })
    //   .end()
  }
})
